//
//  XDropMenuView.m
//  
//
//  Created by Veer on 17/7/10.
//  Copyright © 2017年 Veer. All rights reserved.
//

#import "XDropMenuView.h"


#define MenuTextColorNormal  RGB(56, 56, 56)    // 菜单正常状态颜色
#define MenuTextColorHighlight  RGB(56, 56, 56)    // 菜单选择状态颜色
#define CellTextColorNormal  RGB(51, 51, 51)    // cell正常状态颜色
#define CellTextColorHighlight  RGB(252, 83, 92)    // cell选择状态颜色
#define BottomLineColor  RGB(213, 213, 213)    // 底部线颜色


static const CGFloat cellHeight = 44.0f;

@implementation XMenuModel



@end


@interface XMenuCell()

@property (nonatomic, assign) NSInteger leftMargin;


@property (nonatomic,retain) UIView *bgView;
@property (nonatomic,retain) UIView *point;
@property (nonatomic,retain) UILabel *textL;

@property (nonatomic,strong)UIImageView *iconImgView;
@property (nonatomic,strong)UIImageView *selectedIcon;

@property (nonatomic, assign) BOOL setSelected;

@end

@implementation XMenuCell


- (void)setLeftMargin:(NSInteger)leftMargin
{
    _leftMargin = leftMargin;
    
    self.selectedIcon.x = leftMargin;
    self.textL.x = CGRectGetMaxX(self.selectedIcon.frame) + 10;
    
}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        
        self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, cellHeight)];
        [self.contentView addSubview:_bgView];
        
        self.iconImgView = [UIImageView new];
        self.iconImgView.image = [UIImage imageNamed:@""];
        self.iconImgView.frame = CGRectMake(15, (cellHeight - 18) * 0.5, 18, 18);
        [self.bgView addSubview:self.iconImgView];
        
        CGFloat selectedIconX = SCREEN_WIDTH - 15 - 24;
        self.selectedIcon = [UIImageView new];
        self.selectedIcon.image = [UIImage imageNamed:@"ic_check_mark"];
        self.selectedIcon.frame = CGRectMake(selectedIconX, (cellHeight - 24) * 0.5, 24, 24);
        [self.bgView addSubview:self.selectedIcon];
        self.selectedIcon.hidden = YES;
        
        CGFloat textX = self.leftMargin > 0 ?  self.leftMargin : 45;
        self.textL = [[UILabel alloc] initWithFrame:CGRectMake(textX, 0,300, cellHeight)];
        self.textL.textColor = CellTextColorNormal;
        self.textL.font = VRFont(16);
        [self.bgView addSubview:_textL];
        
        UIView *hLineView = [[UIView alloc] init];
        hLineView.frame = CGRectMake(45, cellHeight - 0.5, SCREEN_WIDTH - 20, 0.5);
        hLineView.backgroundColor = BottomLineColor;
        [self.bgView addSubview:hLineView];
    }
    return self;
}


#pragma mark - setter && getter
- (void)setSetSelected:(BOOL)setSelected
{
    
    self.selectedIcon.hidden = !setSelected;
//    self.textL.textColor = setSelected ? CellTextColorHighlight : CellTextColorNormal;
}

@end


@interface XDropMenuView()

@property (nonatomic,weak) UIView *superContainerView;


@end

@implementation XDropMenuView
{
    UITableView *listTableView;
    NSInteger currentSelect;
    CGRect orginalFrame;
    BOOL isShow;
    UIView *bgView;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.titleNormalColor = RGB(56, 56, 56);
        self.titleSelectedColor = RGB(56, 56, 56);
        self.itemNormalColor = RGB(56, 56, 56);
        self.buttonNormalImage = @"arrow_down";
        self.buttonSelectedImage = @"trianglered_down";
    }
    return self;
}



/**
 这个为了实现某些功能临时加的，写的有点烂，有空再调整
 */
- (void)setupWithShowOnView:(UIView*)view AllDataArr:(NSMutableArray*)arr showArr:(NSMutableArray *)showArr
{
    
    CGRect frame = self.frame;
    
    self.AllDataArr = arr;
    self.showArr = showArr;
    //        if (!showArr) {
    //            self.showArr = arr;
    //        }
    
    for (int i=0; i < showArr.count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i*(CGRectGetWidth(frame)/showArr.count), 0, CGRectGetWidth(frame)/showArr.count, CGRectGetHeight(frame))];
        button.tag = 100 + i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.backgroundColor = [UIColor whiteColor];
        //            button.layer.borderColor = [UIColor grayColor].CGColor;
        //            button.layer.borderWidth = 0.4;
        button.titleLabel.font = VRFont(self.fonteSize > 0 ? self.fonteSize : 14);
        
        [button setTitleColor:self.titleNormalColor forState:UIControlStateNormal];
        [button setTitleColor:self.titleSelectedColor forState:UIControlStateSelected];
        [button setImage:[UIImage imageNamed:self.buttonNormalImage] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:self.buttonSelectedImage] forState:UIControlStateSelected];
        
        CGSize strSize = [showArr[i] sizeWithFont:button.titleLabel.font];
        CGSize curImageSize = button.currentImage.size;
        
        button.imageEdgeInsets = UIEdgeInsetsMake(0, strSize.width+2, 0, -strSize.width-2);
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -curImageSize.width-2, 0, curImageSize.width+2);
        
        [button setTitle:showArr[i] forState:UIControlStateNormal];

        [self addSubview:button];
        [view addSubview:self];
        
        // 竖线
        if (i != arr.count - 1) {
            UIView *line = [UIView new];
            line.backgroundColor = RGB(205, 205, 205);
            [self addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(button.mas_centerY);
                make.left.mas_equalTo(button.mas_right).with.offset(-1);
                make.size.mas_equalTo(CGSizeMake(0.5, 20));
            }];
        }
        
        //
        currentSelect = 0;
        //            [self selectClum:i Row:0];
        
    }
    
    // 线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.frame = CGRectMake(0, CGRectGetHeight(frame)-0.5, kScreenWidth, 0.5);
    [self addSubview:lineView];
    
    // tableview
    listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.frame), kScreenWidth, SCREEN_HEIGHT - CGRectGetMaxY(self.frame))];
    orginalFrame = CGRectMake(0, CGRectGetMaxY(frame), kScreenWidth, 0);
    listTableView.delegate = self;
    listTableView.dataSource = self;
    listTableView.hidden = YES;
    listTableView.separatorColor = [UIColor grayColor];
    //ChdTable.backgroundColor = [UIColor redColor];
    
    
    bgView = [[UIView alloc] initWithFrame:orginalFrame];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [tap addTarget:self action:@selector(bgViewClick:)];
    [bgView addGestureRecognizer:tap];
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    [view addSubview:bgView];
    
    if ([ listTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [listTableView   setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        
    }
    if ([listTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [listTableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        
    }
    
    [view addSubview:listTableView];
}




- (instancetype)initWithFrame:(CGRect)frame showOnView:(UIView*)view AllDataArr:(NSMutableArray*)arr showArr:(NSMutableArray *)showArr
{
    if (self = [super initWithFrame:frame]) {
        
        // 默认样式
        self.titleNormalColor = RGB(56, 56, 56);
        self.titleSelectedColor = RGB(56, 56, 56);
        self.itemNormalColor = RGB(56, 56, 56);
        self.buttonNormalImage = @"pull_down_selector_normal";
        self.buttonSelectedImage = @"pull_down_selector_normal";
        
        self.AllDataArr = arr;
        self.showArr = showArr;
        self.notShowTitleColum = -1;
        self.superContainerView = view;
//        if (!showArr) {
//            self.showArr = arr;
//        }
        
        for (int i=0; i < showArr.count; i++) {
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(i*(CGRectGetWidth(frame) / showArr.count), 0, CGRectGetWidth(frame)/showArr.count, CGRectGetHeight(frame));
            button.tag = 100 + i;
            [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            button.titleLabel.textAlignment = NSTextAlignmentCenter;
            button.titleLabel.font = VRFont(self.fonteSize > 0 ? self.fonteSize : 18);
            
            button.adjustsImageWhenHighlighted = NO;
            [button setTitleColor:self.titleNormalColor forState:UIControlStateNormal];
//            [button setTitleColor:RGB(190, 17, 17) forState:UIControlStateSelected];
            [button setImage:[UIImage imageNamed:self.buttonNormalImage] forState:UIControlStateNormal];
//            [button setImage:[UIImage imageNamed:@"triangleDown"] forState:UIControlStateSelected];
            
            CGSize strSize = [showArr[i] sizeWithFont:button.titleLabel.font];
            CGSize curImageSize = button.currentImage.size;
            
            button.imageEdgeInsets = UIEdgeInsetsMake(0, strSize.width+4, 0, -strSize.width-4);
            button.titleEdgeInsets = UIEdgeInsetsMake(0, -curImageSize.width-4, 0, curImageSize.width+2);
            
            [button setTitle:showArr[i] forState:UIControlStateNormal];
            [self addSubview:button];
            [view addSubview:self];
            
            //
            currentSelect = 0;
//            [self selectClum:i Row:0];
            
        }
        
        // tableview
        CGRect rect = [self convertRect:self.frame toView:view];

        listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(rect), kScreenWidth, kScreenWidth - CGRectGetMaxY(rect))];
        orginalFrame = CGRectMake(0, CGRectGetMaxY(rect), kScreenWidth, 0);
        listTableView.delegate = self;
        listTableView.dataSource = self;
        listTableView.hidden = YES;
        listTableView.separatorStyle = UITableViewCellSelectionStyleNone;
        
        bgView = [[UIView alloc] initWithFrame:orginalFrame];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [tap addTarget:self action:@selector(bgViewClick:)];
        [bgView addGestureRecognizer:tap];
        bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
        [view addSubview:bgView];
        
        if ([ listTableView respondsToSelector:@selector(setSeparatorInset:)]) {
            
            [listTableView   setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            
        }
        if ([listTableView respondsToSelector:@selector(setLayoutMargins:)]) {
            
            [listTableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
            
        }
        
        [view addSubview:listTableView];
    }
    
    return self;
}

- (void)refreshData:(NSMutableArray *)allDataArray
{
    self.AllDataArr = allDataArray;
    [self realShow];
}

/**
 处理list的展示
 */
- (void)realShow
{
    
    CGRect rect = [self convertRect:self.frame toView:self.superContainerView];
    orginalFrame = CGRectMake(0, CGRectGetMaxY(rect), kScreenWidth, 0);
    
    listTableView.hidden = YES;
    listTableView.height = cellHeight * [_AllDataArr[currentSelect] count];
    [listTableView reloadData];
    
    bgView.frame = orginalFrame;
    bgView.height = kScreenHeight - orginalFrame.origin.y;
    
    listTableView.frame = orginalFrame;
    listTableView.hidden = NO;
    
//    UIButton *btn = [self viewWithTag:currentSelect + 100];//self.subviews[currentSelect];
    
    [UIView animateWithDuration:0.2 animations:^{
        
//        if (cellHeight * [_AllDataArr[currentSelect] count] > kScreenHeight - orginalFrame.origin.y) {
//            listTableView.mj_h = kScreenHeight - orginalFrame.origin.y;
//        }else{
//            listTableView.mj_h = cellHeight * [_AllDataArr[currentSelect] count];
//        }
        if ([_AllDataArr[currentSelect] count] > 4) {
            listTableView.height = 4.5 * cellHeight;
        }else{
            listTableView.height = cellHeight * [_AllDataArr[currentSelect] count];
        }
    }];
}

- (void)hideCurrent
{
    
    UIButton *btn = [self viewWithTag:100 + currentSelect];
    btn.selected = NO;
    
    [UIView animateWithDuration:0.2 animations:^{
        
        [btn setImage:[UIImage imageNamed:self.buttonNormalImage] forState:UIControlStateNormal];
        listTableView.frame = orginalFrame;
        [btn setTitleColor:self.titleNormalColor forState:UIControlStateNormal];
//        btn.imageView.transform = CGAffineTransformMakeRotation(0);
    }];
    bgView.frame = orginalFrame;
}


#pragma mark - action
- (void)bgViewClick:(UITapGestureRecognizer*)tap
{
    [self hideCurrent];
    isShow = NO;
    bgView.frame = orginalFrame;
}


- (void)buttonClick:(UIButton *)button
{
    
    // 点击了本按钮
    if (button.tag - 100 == currentSelect) {
        
        if (isShow) {
            [self hideCurrent];
        }else{
            [self showIndex:button.tag - 100];
        }
        isShow = !isShow;
    }else{
        
        if (isShow) {
            
            [self hideCurrent];
            [self showIndex:button.tag - 100];
        }else{
            
            [self showIndex:button.tag - 100];
        }
        isShow = YES;
    }
}

- (void)showIndex:(NSInteger)index
{
    
    UIButton *btn = [self viewWithTag:index + 100];
    
    [btn setImage:[UIImage imageNamed:self.buttonSelectedImage] forState:UIControlStateNormal];
    [btn setTitleColor:self.titleSelectedColor forState:UIControlStateNormal];
    [UIView animateWithDuration:0.2 animations:^{

//        btn.imageView.transform = CGAffineTransformMakeRotation(0.01-M_PI);
    }];
    
    
    currentSelect = index;
    
    if ([self.delegate respondsToSelector:@selector(dropMenuView:didSelectColum:)]) {
        [self.delegate dropMenuView:self didSelectColum:currentSelect];
    }
    [self realShow];
}


- (void)selectClum:(NSInteger)colum Row:(NSInteger)row
{
    //默认选中第一个
    NSArray *temp = self.AllDataArr[colum];
    for (int i = 0; i < temp.count; i++) {
        XMenuModel *model = temp[i];
        if (i == row) {
            model.isSelect = YES;
        }else{
            model.isSelect = NO;
        }
    }
    
    UIButton *btn = [self viewWithTag:100 + colum];
    XMenuModel *model = self.AllDataArr[colum][row];
    
    [btn setTitle:model.name forState:UIControlStateNormal];
    
    CGSize strSize = [model.name sizeWithFont:btn.titleLabel.font];
    CGSize curImageSize = btn.currentImage.size;
    
    if ((strSize.width + curImageSize.width) > btn.width) {
        
        CGFloat leftMargin = btn.width - curImageSize.width - 6;
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, leftMargin, 0, -leftMargin);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -curImageSize.width + 2, 0, curImageSize.width + 4);
    }else{
        
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, strSize.width+2, 0, -strSize.width-2);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -curImageSize.width-2, 0, curImageSize.width+2);
    }
    
}


#pragma mark - 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_AllDataArr[currentSelect] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *chdResuseID = @"CHD_RESUSE";
    
    XMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:chdResuseID];
    
    if (cell == nil) {
        cell = [[XMenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:chdResuseID];
        
        if (self.leftMargin > 0) {
            cell.leftMargin = self.leftMargin;
        }
    }
    
    XMenuModel *model = [_AllDataArr[currentSelect] objectAtIndex:indexPath.row];
    cell.textL.text = model.name;
    cell.imageView.image = [UIImage imageNamed:model.imageName];

    if (model.isSelect) {
        cell.setSelected = YES;
    }else{
        cell.setSelected = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    //*************  本段代码用于选择相同选项时不在回调，不需要可注掉  ****************
    XMenuModel *modelLast = self.AllDataArr[currentSelect][indexPath.row];
    if (modelLast.isSelect) {
        [self hideCurrent];
        isShow = NO;
        
        return;
    }
    //*************  本段代码用于选择相同选项时不在回调，不需要可注掉  ****************
    [self selectClum:currentSelect Row:indexPath.row];
    
    [self hideCurrent];
    isShow = NO;
    XMenuModel *model = self.AllDataArr[currentSelect][indexPath.row];
    if ([self.delegate respondsToSelector:@selector(dropMenuView:didSelectRowAtColum:Row:model:)]) {
        [self.delegate dropMenuView:self didSelectRowAtColum:currentSelect Row:indexPath.row model:model];
    }
    
}


#pragma mark setter && getter
- (void)setTitleNormalColor:(UIColor *)titleNormalColor
{
    _titleNormalColor = titleNormalColor;
    for (UIView *subView in self.subviews) {
        
        if ([subView isKindOfClass:[UIButton class]]) {
            
            [((UIButton *)subView) setTitleColor:titleNormalColor forState:UIControlStateNormal];
        }
    }
}


- (void)setTitleSelectedColor:(UIColor *)titleSelectedColor
{
    _titleSelectedColor = titleSelectedColor;
    for (UIView *subView in self.subviews) {
        
        if ([subView isKindOfClass:[UIButton class]]) {
            
            [((UIButton *)subView) setTitleColor:titleSelectedColor forState:UIControlStateSelected];
        }
    }
}


- (void)setButtonNormalImage:(NSString *)buttonNormalImage
{
    _buttonNormalImage = buttonNormalImage;
    for (UIView *subView in self.subviews) {
        
        if ([subView isKindOfClass:[UIButton class]]) {
            
            [((UIButton *)subView) setImage:[UIImage imageNamed:buttonNormalImage] forState:UIControlStateNormal];
        }
    }
}

- (void)setButtonSelectedImage:(NSString *)buttonSelectedImage
{
    _buttonSelectedImage = buttonSelectedImage;
    
    for (UIView *subView in self.subviews) {
        
        if ([subView isKindOfClass:[UIButton class]]) {
            
            [((UIButton *)subView) setImage:[UIImage imageNamed:buttonSelectedImage] forState:UIControlStateSelected];
        }
    }
}


@end
